//
//  MFWDownloadHeadChecker.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-8-28.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "MFWDownloadHeadChecker.h"

@interface MFWDownloadHeadChecker()
{
}

@property (nonatomic, copy) NSDictionary *dict;

@end

@implementation MFWDownloadHeadChecker

- (id)initWithHeadDict:(NSDictionary *)aDict
{
    self = [super init];
    if (self)
    {
        self.dict = aDict;
        [self loadOffsets];
    }
    return self;
}

+ (id)checkWithHeadDict:(NSDictionary *)aDict
{
    return [[MFWDownloadHeadChecker alloc] initWithHeadDict:aDict];
}

- (BOOL)isKeepAlive
{
    return YES;
    
    __block BOOL alive = YES;
    [self.dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
        if ([key.lowercaseString rangeOfString:@"connection"].length > 0)
        {
            if ([value.lowercaseString rangeOfString:@"close"].length > 0)
            {
                alive = NO;
            }
        }
    }];
    
    return alive;
}

- (void)loadOffsets
{
    NSString *rangeString = [self.dict stringValueForKey:@"Content-Range"];
    NSScanner *scanner = [NSScanner scannerWithString:rangeString];
    
    
    _beginOffset = -1;
    _endOffset =  -1;
    _curLength = 0;
    _fileLength = 0;
    
    [scanner scanString:@"bytes" intoString:nil];
    BOOL findBegin = [scanner scanLongLong:&_beginOffset];
    
    [scanner scanString:@"-" intoString:nil];
    BOOL findEnd = [scanner scanLongLong:&_endOffset];
    
    [scanner scanString:@"/" intoString:nil];
    [scanner scanLongLong:&_fileLength];
    
    if (findBegin && findEnd)
    {
        _curLength = _endOffset - _beginOffset + 1;
    }
}

- (NSString*)lastUpdateTime
{
    return [self.dict stringValueForKey:@"Last-Modified"];
}

- (NSString*)eTag
{
    return [self.dict stringValueForKey:@"ETag"];
}

- (BOOL)checkNewestByETag:(NSString *)aETag lastUpdateTime:(NSString *)aLastUpdateTime
{
    NSString *newETag = self.eTag;
    NSString *newLastModified = self.lastUpdateTime;
    if ( (newETag.length > 0) != (aETag.length > 0) )
    {
        return NO;
    }
    if ( (newLastModified.length > 0 ) != (aLastUpdateTime.length > 0) )
    {
        return NO;
    }
    if (newETag.length && aETag.length && ![newETag isEqualToString:aETag])
    {
        return NO;
    }
    if (newLastModified.length
        && aLastUpdateTime.length
        && ![newLastModified isEqualToString:aLastUpdateTime])
    {
        return NO;
    }
    return YES;
}

- (NSString*)redirectUrl
{
    return [self.dict valueForKey:@"Location"];
}




@end
